import { UserOutlined, CheckCircleFilled, QuestionCircleOutlined } from '@ant-design/icons';
import { useQuery } from '@tanstack/react-query';
import {
  Card,
  Input,
  Space,
  Button,
  Image,
  Form,
  Modal,
  Select,
  Avatar,
  message,
  InputNumber,
} from 'antd';
import { useState, useEffect } from 'react';

import PayModal from './payModal';

import commonService from '@/api/services/commonService';
import accountMemo from '@/assets/img/accountMemo.png';

import './index.css';

const roleMap: any = {
  1: '店铺用户',
  2: '设计师',
  3: '分销商',
};
const memberLevelMap: any = {
  1: '普通会员',
  2: '铜卡会员',
  3: '银卡会员',
  4: '金卡会员',
};

const roleOptions = Object.keys(roleMap).map((key) => {
  return { label: roleMap[key], value: Number(key) };
});

export default function AccountPage() {
  const { data = {} } = useQuery({
    queryKey: ['/member/myAccount', {}],
    queryFn: async () => {
      return commonService.getCustomApi('/member/myAccount', {});
    },
  });

  const [show, setShow] = useState(false);
  const [info, setInfo] = useState<any>({});
  const [currentLevelId, setCurrentLevelId] = useState<string>('2');
  const [visible, setVisible] = useState(false);
  const [showPay, setShowPay] = useState(false);
  const [memberRechargeId, setMemberRechargeId] = useState('');

  const toUpgrade = () => {
    commonService.getCustomApi('/member/apply/getMemberApply', {}).then((res) => {
      if (!res) {
        setShow(true);
      } else {
        setInfo(res);
        message.warning('审核中！');
      }
    });
  };

  const handleCopy = () => {
    navigator.clipboard.writeText(data.tuiGuangUrl).then(() => {
      message.success('复制成功！');
    });
  };

  const memberList: any = [
    { label: '铜卡会员', price: 199, id: '2' },
    { label: '银卡会员', price: 399, id: '3' },
    { label: '金卡会员', price: 699, id: '4' },
  ];

  const toPay = () => {
    if (!currentLevelId) {
      message.error('请选择会员等级！');
      return false;
    }
    commonService
      .postCustomApi('/member/member-level-record/add', { levelId: currentLevelId })
      .then((res) => {
        setMemberRechargeId(res.id);
        setShowPay(true);
      });
  };

  const handleOk = () => {
    setShowPay(false);
  };

  return (
    <Space direction="vertical" size="large" className="w-full">
      <Card title="个人信息" bordered={false}>
        <div className="flex items-center justify-between">
          <div className="flex items-center">
            <div className="mr-[60px] text-[20px] text-[#363A44]">个人信息</div>
            <div className="mr-[20px] flex flex-col items-center">
              {data.memberView?.avatar ? (
                <Image src={data.memberView?.avatar} width="140" preview={false} />
              ) : (
                <Avatar size={140} style={{ backgroundColor: '#FD7901' }} icon={<UserOutlined />} />
              )}
              {/* {data.memberView?.userType === 1 ? (
                <Button
                  className="mt-[20px] h-[40px] w-[100px]"
                  type="primary"
                  ghost
                  onClick={toUpgrade}
                >
                  编辑
                </Button>
              ) : (
                ''
              )} */}
            </div>
            <div
              className="flex flex-col gap-[10px] text-[#686B73]"
              style={{ alignSelf: 'flex-start' }}
            >
              <div>ID: {data.memberView?.id}</div>
              <div>
                身份:
                {data.memberView?.userType === 3
                  ? memberLevelMap[data.memberView?.userLevel]
                  : roleMap[data.memberView?.userType]}
              </div>
              {data.memberView?.expireTime ? (
                <div>会员过期时间: {data.memberView?.expireTime}</div>
              ) : null}
              <div>账号: {data.memberView?.loginName}</div>
              <div>姓名: {data.memberView?.userName}</div>
            </div>
          </div>
          <div className="flex flex-col gap-[10px]">
            <div className="flex">
              <div style={{ flexShrink: 0 }}>我的推广二维码：</div>
              <div className="flex h-[160px] w-[160px] items-center justify-center">
                <Image src={`data:image/jpeg;base64,${data.qrCode}`} width={150} height={150} />
              </div>
            </div>
            <div className="flex items-center gap-[10px]">
              <div style={{ flexShrink: 0 }}>我的推广链接：</div>
              <Input className="w-[280px]" value={data.tuiGuangUrl} />
              <Button className="h-[40px] w-[100px]" onClick={handleCopy}>
                复制
              </Button>
            </div>
          </div>
        </div>
        <div className="mb-[20px] ml-[140px] mt-[40px] h-[1px] bg-[#E8E9EC]" />
        <div className="flex items-center justify-between">
          <div className="flex items-center">
            <div className="mr-[60px] text-[20px] text-[#363A44]">
              升级会员
              <QuestionCircleOutlined
                style={{ cursor: 'pointer' }}
                onClick={() => setVisible(true)}
              />
            </div>
            <div className="mr-[20px] flex items-center gap-[20px]">
              {memberList.map((item: any) => (
                <div
                  onClick={() => setCurrentLevelId(item.id)}
                  key={item.id}
                  className={`member-item ${
                    currentLevelId === item.id ? 'member-item-active' : ''
                  } relative flex h-[120px] w-[140px] flex-col items-center justify-center`}
                >
                  {currentLevelId === item.id ? (
                    <CheckCircleFilled className="absolute left-[6px] top-[6px] text-[24px] text-[#FD7901]" />
                  ) : null}
                  <p className="text-[20px] text-[#363A44]">{item.label}</p>
                  <p className="text-[16px] text-[#686B73]">
                    <span className="text-[24px] text-[#FD7901]">￥{item.price}</span>/年
                  </p>
                </div>
              ))}
              <Button onClick={toPay} type="primary" size="large" className="ml-[20px] w-[140px]">
                去支付
              </Button>
            </div>
          </div>
        </div>
        <div className="mb-[20px] ml-[140px] mt-[40px] h-[1px] bg-[#E8E9EC]" />
        <div className="flex items-center justify-between">
          <div className="flex items-center">
            <div className="mr-[60px] text-[20px] text-[#363A44]">账户安全</div>
            <div className="mr-[20px] flex flex-col gap-[10px] text-[20px] text-[#363A44]">
              <div className="flex">
                <span className="text-[#686B73]">手机：</span>
                {data.memberView?.phoneNumber}
              </div>
              <div className="flex">
                <span className="text-[#686B73]">邮箱：</span>
                {data.memberView?.email}
              </div>
            </div>
          </div>
        </div>
      </Card>

      <Image
        width={200}
        style={{ display: 'none' }}
        src={accountMemo}
        preview={{
          visible,
          src: accountMemo,
          onVisibleChange: (value) => setVisible(value),
        }}
      />
      <PayModal
        show={showPay}
        onOk={handleOk}
        memberRechargeId={memberRechargeId}
        onClose={() => setShowPay(false)}
      />

      {/* <Card title="密码修改">
        <Form labelCol={{ span: 4 }} wrapperCol={{ span: 18 }} layout="horizontal">
          <Form.Item<any> label="新密码" name="password" required>
            <Input type="password" />
          </Form.Item>
          <Form.Item<any> label="确认密码" name="confirmPassword" required>
            <Input type="password" />
          </Form.Item>
        </Form>
      </Card> */}

      <UpgradeModal show={show} info={info} onCancel={() => setShow(false)} />
    </Space>
  );
}

function UpgradeModal({ show, info, onCancel }: any) {
  const [form] = Form.useForm();
  useEffect(() => {
    form.setFieldsValue({ ...info });
  }, [info, form]);

  const handleApply = async () => {
    await form.validateFields();
    const params = form.getFieldsValue();
    commonService.putCustomApi('/member/apply/submitApply', params).then(() => {
      message.success('申请成功');
      onCancel();
    });
  };
  return (
    <Modal title="编辑" open={show} onOk={handleApply} onCancel={onCancel} centered>
      <Form
        initialValues={info}
        form={form}
        labelCol={{ span: 4 }}
        wrapperCol={{ span: 18 }}
        layout="horizontal"
      >
        <Form.Item<any>
          label="真实姓名"
          name="name"
          rules={[{ required: true, whitespace: true, message: '请输入名字' }]}
        >
          <Input />
        </Form.Item>
        <Form.Item<any>
          label="真实地址"
          rules={[{ required: true, whitespace: true, message: '请输入地址' }]}
          name="address"
        >
          <Input />
        </Form.Item>
        <Form.Item<any>
          label="手机号"
          name="mobile"
          rules={[{ required: true, message: '请输入手机号' }]}
        >
          <InputNumber style={{ width: '100%' }} />
        </Form.Item>
        <Form.Item<any>
          label="申请成为"
          name="userType"
          rules={[{ required: true, message: '请选择角色' }]}
        >
          <Select options={roleOptions} />
        </Form.Item>
        <Form.Item<any>
          label="申请说明"
          name="reason"
          rules={[{ required: true, whitespace: true, message: '请输入申请说明' }]}
        >
          <Input />
        </Form.Item>
        {/* <Form.Item<any> label="拒绝原因" name="returnedReason">
          <TextArea />
        </Form.Item> */}
      </Form>
    </Modal>
  );
}
